package com.cherry.androidcode.upload

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.IOException

//Track upload progress
class ProgressRequestBody1(val requestBody: RequestBody, var callback: progressCallback? = null) :
    RequestBody() {

    override fun contentType(): MediaType? {
        return requestBody.contentType()
    }

    @Throws(IOException::class)
    override fun contentLength(): Long {
        return requestBody.contentLength()
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        if (sink is Buffer
            || sink.toString()
                .contains("com.android.tools.profiler.support.network.HttpTracker\$OutputStreamTracker")
        ) {
            requestBody.writeTo(sink)
        } else {
            val bufferedSink = Okio.buffer(sink(sink))
            requestBody.writeTo(bufferedSink)
            bufferedSink.close()
        }
    }

    private fun sink(sink: Sink): Sink {
        return object : ForwardingSink(sink) {
            var bytesWritten = 0L
            var contentLength = 0L
            var lastProgress = 0

            @Throws(IOException::class)
            override fun write(source: Buffer, byteCount: Long) {
                super.write(source, byteCount)
                if (contentLength == 0L) {
                    contentLength = contentLength()
                }
                bytesWritten += byteCount
                val currentProgress = (bytesWritten * 100 / contentLength).toInt()
                if (currentProgress > lastProgress) {
                    lastProgress = currentProgress
                    updateProgress(lastProgress, bytesWritten, contentLength)
                }
            }
        }
    }

    private fun updateProgress(progress: Int, currentSize: Long, totalSize: Long) {
        callback?.invoke(progress, currentSize, totalSize)
    }

}